<?php

/**
 * @file
 *   
 * EM Registration Submits and Validations for Form steps.
 */

// Validation Fucntions
function _register_parent_demographic_info_validate($form, &$form_state) {
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $form_state['values']['email'])) {
        form_set_error('invalid_email', t('Please enter a valid email.'));
    }
    if (strlen($form_state['values']['password']) < 5) {
        form_set_error('password_length', t('Passwords must be more than 4 characters'));
    }
    if ($form_state['values']['password'] != $form_state['values']['confirm_password']) {//confirm_password
        form_set_error('password_match', t('Passwords don\'t match'));
    }
}
function _register_yp_demographic_info_validate($form, &$form_state){
    if (strlen($form_state['values']['yp_email'])>4&&!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $form_state['values']['yp_email'])) {
        form_set_error('invalid_email', t('Please enter a valid email.'));
    }
//    if (strlen($form_state['values']['yp_password']) < 5) {
//        form_set_error('password_length', t('Passwords must be more than 4 characters'));
//    }
//    if ($form_state['values']['yp_password'] != $form_state['values']['yp_confirm_password']) {//confirm_password
//        form_set_error('password_match', t('Passwords don\'t match'));
//    }
}
function _register_parent_address_validate($form, &$form_state) {
    $values = $form_state['values'];
    $form_key = "parent_addresses";
    
    foreach ($values[$form_key] as $address_data) {
        
//        if ($address_data['zip']<9000 || strlen($address_data['zip'])!=5) {
//            form_set_error('invalid_zip', t('Please enter a valid zip'));
//        }
      
    }
}
function register_parent_eligibility_validate($form, &$form_state) {
    
}

// Submit Functions
function _registration_parent_pre_registration_submit($form, &$form_state) {
    $vt_minAge = strtolower($form_state['values']["min_age"]);
    $vt_isUnionMember = strtolower($form_state['values']["is_union_member"]);
    $vt_minIncome = strtolower($form_state['values']["is_min_income"]);
    $vt_haveAgent = strtolower($form_state['values']["have_agent"]);

    $vb_OptimalAnswer = ($vt_minAge == "yes") && ($vt_haveAgent == "yes");

    if($vt_isUnionMember == "no"){
        $vb_OptimalAnswer = $vb_OptimalAnswer && ($vt_minIncome == "yes");
    }
    else{
        $vb_OptimalAnswer = $vb_OptimalAnswer && ($vt_isUnionMember == "yes");
    }
    
    //Set Error
    if(!$vb_OptimalAnswer){
        $steps = MformsSteps::getInstance(mforms_store_get('parent'));
        $steps->overrideNext('_registration_parent_reg_failed');
    }
}
function _register_parent_demographic_info_submit($form, &$form_state) {
    $values = $form_state['values'];

    //set up the user fields
    $fields = array(
        'name' => $values["username"],
        'mail' => $values["email"],
        'pass' => $values["password"],
        'status' => 1,
        'init' => 'email address',
        'roles' => array(
            DRUPAL_AUTHENTICATED_RID => 'authenticated user',
        ),
    );

    $user_account = user_save(NULL, $fields); //Add Data in Drupal user table
    $user_id = $user_account->uid;
    
    $new_user = db_insert('la_users')->fields(array(
                'user_id' => $user_id,
                'first_name' => $values['first_name'],
                'middle_name' => $values['middle_name'],
                'last_name' => $values['last_name'],
                'aka_first_name' => "",
                'aka_last_name' => "",
                'dob' => $values['dob']['year'] . "-" . $values['dob']['month'] . "-" . $values['dob']['day'],
                'cell_phone' => $values['cell_phone'],
                'phone_number' => $values['phone_number'],
                'marital_status' => $values['marital_status'],
                'gender' => "",
                'ethnicity' => "",
                'ca_resident' => $values['ca_resident'],
                'discriminator' => "P",
            ))->execute();

    //Store alternate contact methods in contact_methods methods 
    foreach ($values['alternate_contact'] as $alternate_contact) {
        $carrier = "";
        if (strtolower($alternate_contact) == "texting") {
            $carrier = $values['text_carrier'];
        }

        $contact_method = db_insert('contact_methods')->fields(array(
                    'contact_method_title' => $alternate_contact,
                    'users_user_id' => $user_id,
                    'carrier' => $carrier,
                ))->execute();
    }
    
    //Login New User
    global $user;  
    $uid = user_authenticate($values["username"], $values["password"]);    
    $arr = array ('name' => $values["username"], 'pass' => $values["password"]);
    if ($uid){
      $user = user_load($uid);
      user_login_finalize($arr);
    }
}
function _register_yp_demographic_info_submit($form, &$form_state){
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        
        // not needed since YP does not have account
        /*$fields = array(
            'name' => $values["username"],
            'mail' => $values["email"],
            'pass' => $values["password"],
            'status' => 1,
            'init' => 'email address',
            'roles' => array(
                DRUPAL_AUTHENTICATED_RID => 'authenticated user',
            ),
        );*/
        $new_user = db_insert('la_users')->fields(array(
                'user_id' => 0,
                'first_name' => $values['yp_first_name'],
                'middle_name' => $values['yp_middle_name'],
                'last_name' => $values['yp_last_name'],
                'aka_first_name' => $values['yp_aka_first_name'],
                'aka_last_name' => $values['yp_last_last_name'],
                'dob' => $values['yp_dob']['year'] . "-" . $values['yp_dob']['month'] . "-" . $values['yp_dob']['day'],
                'cell_phone' => $values['yp_cell_phone'],
                'phone_number' => '',
                'marital_status' => '',
                'gender' => $values['yp_gender'],
                'ethnicity' => $values['yp_ethnicity'],
                'ca_resident' => $values['yp_ca_resident'],
                'discriminator' => "YP",
            ))->execute();
        
        $user_user = db_insert('users_has_users')->fields(array(
                'users_user_id' => $user_id,
                'users_user_id1' => $new_user,
            ))->execute();

        //Store alternate contact methods in contact_methods methods 
        foreach ($values['yp_alternate_contact'] as $alternate_contact) {
            $carrier = "";
            if (strtolower($alternate_contact) == "texting") {
                $carrier = $values['yp_text_carrier'];
            }

            $contact_method = db_insert('contact_methods')->fields(array(
                        'contact_method_title' => $alternate_contact,
                        'users_user_id' => $new_user,
                        'carrier' => $carrier,
                    ))->execute();
        }
    }
}
function _register_parent_address_submit($form, &$form_state) {
    //return;
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "parent_addresses";

        unset($values[$form_key]["add_address"]);
        unset($values[$form_key]["remove_address"]);
        foreach ($values[$form_key] as $address_data) {
            $address = db_insert('addresses')->fields(array(
                        'users_user_id' => $user_id,
                        'mailing_address' => $address_data['mailing_address'],
                        'apartment_number' => $address_data['apt_no'],
                        'city' => $address_data['city'],
                        'state' => $address_data['state'],
                        'zip' => $address_data['zip'],
                        'adults' => $address_data['no_of_adults_address'],
                        'children' => $address_data['no_of_children_address'],
                        'accept_mailings' => $address_data['mail_at_address'],
                    ))->execute();
        }
    }
}
function _register_parent_eligibility_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "parent_unions";

        unset($values[$form_key]["add_union"]);
        unset($values[$form_key]["remove_union"]);
        foreach ($values[$form_key] as $union_data) {
            $union = db_insert('users_has_unions')->fields(array(
                        'user_id' => $user_id,
                        'union_id' => $union_data['union_id'],
                        'union_number' => $union_data['union_no'],
                    ))->execute();
        }
        $agency = db_insert('agencies')->fields(array(
                        'users_user_id' => $user_id,
                        'agency_name' => $values['agency'],
                        'agent_name' => $values['agent_name'],
                        'agency_phone' => $values['agent_phone'],
                    ))->execute();
    }
}
function _register_parent_education_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "parent_schools";

        unset($values[$form_key]["add_school"]);
        unset($values[$form_key]["remove_school"]);
        foreach ($values[$form_key] as $school_data) {
            $school = db_insert('schools')->fields(array(
                        'users_user_id' => $user_id,
                        'school_name' => $school_data['school_name'],
                        'city' => $school_data['school_city'],
                        'state' => $school_data['school_state'],
                        'zip' => $school_data['school_zip'],
                        'school_type' => $school_data['school_type'],
                        'years_spent' => $school_data['school_years'],
                        'graduation_level' => $school_data['school_grade_level'],
                        'is_graduated' => $school_data['has_graduated'],
                    ))->execute();
        }
    }
}
function _register_parent_waivers_releases_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "parent_waivers_releases";
        
        $union = db_insert('waivers_and_releases')->fields(array(
                        'users_user_id' => $user_id,
                        'code_of_conduct_confirmation' => !empty($values['code_of_conduct']) ? 1 : 0,
                        'photo_release_confirmation' => !empty($values['photo_release']) ? 1 : 0,
                        'video_release_confirmation' => !empty($values['video_release']) ? 1 : 0,
                        'emergency_contact_first' => $values['emergency_contact']['emergency_contact_first'],
                        'emergency_contact_last' => $values['emergency_contact']['emergency_contact_last'],
                        'emergency_phone' => $values['emergency_contact']['emergency_phone'],
                        'emergency_address' => $values['emergency_contact']['emergency_address'],
                        'emergency_apartment' => $values['emergency_contact']['emergency_apt'],
                        'emergency_city' => $values['emergency_contact']['emergency_city'],
                        'emergency_state' => $values['emergency_contact']['emergency_state'],
                        'emergency_zip' => $values['emergency_contact']['emergency_zip'],
                        'relationship_to_participant' => $values['emergency_contact']['relationship_to_participant'],
                        'insurance_name' => $values['name_of_insurance'],
                        'medical_insurance_number' => $values['medical_insurance_no'],
                        'any_medical_issue' => !empty($values['disabilities']) ? 1 : 0,
                        'medical_issue_explanation' => !empty($values['disability_explanation']) ? 1 : 0,
                        'any_alergy' => !empty($values['medication_allergy']) ? 1 : 0,
                        'allergy_explanation' => $values['allergy_explanation'],
                        'any_medication' => $values['taking_medication'],
                        'medication_explanation' => !empty($values['medication_explanation']) ? 1 : 0,
                    ))->execute();
    }
}
function _register_parent_additional_info_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        
        $user = db_update('la_users')->fields(array(
                    'more_info' => !empty($values['more_info']) ? 1 : 0,
                    'education_counseling' => !empty($values['education_counseling']) ? 1 : 0,
                    'family_counseling' => !empty($values['family_counseling']) ? 1 : 0,
                    'referred_by_google' => !empty($values['heard_from']["Google"]) ? 1 : 0,
                    'referred_by_friend' => !empty($values['heard_from']["Friend"]) ? 1 : 0
                ))
                ->condition('user_id', $user_id)
                ->execute();
    }
}
function _registration_parent_reg_failed_submit($form, &$form_state) {
    $form_state['values']["next_step"] = "_registration_parent_pre_registration";
    mforms_clean("parent");
}
function _registration_add_yp_submit($form, &$form_state) {
    $steps = MformsSteps::getInstance(mforms_store_get('parent'));
    $steps->overrideNext('_register_yp_demographic_info');
}